package cn.harvest.storage.web.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.harvest.storage.vo.EmployeeVo;

public class VisitFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rep = (HttpServletResponse) response;
		String uri = req.getRequestURI();
		boolean isLayout = false;
		isLayout = isLayout || uri.indexOf(".html") < 0;
		isLayout = isLayout || uri.indexOf("index.html") >= 0;
		isLayout = isLayout || uri.indexOf("header.html") >= 0;
		isLayout = isLayout || uri.indexOf("main.html") >= 0;
		isLayout = isLayout || uri.indexOf("footer.html") >= 0;
		isLayout = isLayout || uri.indexOf("menu.html") >= 0;
		isLayout = isLayout || uri.indexOf("error.html") >= 0;
		isLayout = isLayout || uri.indexOf("editUser.html") >= 0;
		isLayout = isLayout || uri.indexOf("editPass.html") >= 0;
		isLayout = isLayout || uri.indexOf("login.html") >= 0;
						   
		if (isLayout) {
			chain.doFilter(req, rep);
		} else {
			HttpSession session = req.getSession();
			EmployeeVo operator = (EmployeeVo) session.getAttribute("operator");
			if (null != operator) {
				List permissions = operator.getOperatorPermissionList();
				boolean isAllowPassed = false;
				for (int i = 0; i < permissions.size(); i++) {
					Object[] objArr = (Object[]) permissions.get(i);
//					System.out.println("====================>>>>>>>"+objArr[1]);
					if (uri.indexOf(objArr[1].toString()) >= 0) {
						isAllowPassed = true;
						break;
					}
				}
				if (isAllowPassed) {
					chain.doFilter(req, rep);
				} else {
					rep.sendRedirect("/storage/error.html");
				}
			}
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}
}
